import {createRouter, createWebHashHistory, createWebHistory} from 'vue-router'
import {useUserStore} from '@/store'
import NProgress from 'nprogress'
import tool from '@/utils/tool'
import 'nprogress/nprogress.css'

import routes from './webRouter.js'

const title = import.meta.env.VITE_APP_TITLE
const defaultRoutePath = '/'
const whiteRoute = ['login', 'mineDoc', 'interfaceList', 'interfaceCode', 'signature', 'h5login']

const router = createRouter({
    history: createWebHistory(),
    routes
})

router.beforeEach(async (to, from, next) => {
    NProgress.start()
    // 白名单路由
    if (whiteRoute.includes(to.name)) {
        next()
        return
    }

    // 未登录跳登录
    if (!tool.local.get(import.meta.env.VITE_APP_TOKEN_PREFIX)) {
        next({name: 'login', query: {redirect: to.fullPath}})
        return
    }

    // 登录状态下
    if (to.name === 'login') {
        next({path: defaultRoutePath})
        return
    }

    // 用户信息无效
    const userStore = useUserStore()
    if (!userStore.user && userStore.user == undefined) {
        const data = await userStore.requestUserInfo()
        data && next({path: to.path, query: to.query})
        return
    }
    next()
})

router.afterEach((to, from) => {
    let toTitle = to.meta.title ? to.meta.title : to.name
    document.title = `${toTitle} - ${title}`
    NProgress.done()
})

router.onError(error => {
    console.log(error)
    NProgress.done();
});


export default router